Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → Assign Function to a Variable

Python Functions

Assign Function to a Variable

In Python, functions are first-class citizens. This means they can be treated like any other object – you can assign them to variables, pass them as arguments to other functions, return them from functions, and even store them in data structures like lists or dictionaries. This flexibility is a powerful feature that enables higher-order functions and functional programming paradigms.Let's explore assigning functions to variables with several examples:

1. Basic Assignment

The simplest way to assign a function to a variable is to just use the assignment operator (`=`). The variable then becomes a reference to the function object.
Assign Function to a Variable in Python def greet(name): """A simple greeting function.""" print(f"Hello, {name}!") # Assign the function to a variable greeting_function = greet # Call the function using the variable greeting_function("Alice") # The original function name still works greet("Bob")

Output

Hello, Alice! Hello, Bob!
Here, `greeting_function` and `greet` both point to the same function object in memory. Modifying one doesn't affect the other (unless you're modifying the function's internal state, which we'll discuss later).

2. Assigning Anonymous (Lambda) Functions

Lambda functions are small, anonymous functions defined using the `lambda` keyword. They are often assigned to variables for conciseness.
Assigning Anonymous (Lambda) Functions in python # Assign a lambda function to a variable square = lambda x: x * x # Use the variable to call the lambda function result = square(5) print(result) # Another example with multiple arguments add = lambda x, y: x + y sum_result = add(10, 20) print(sum_result)

Output

25 30
Lambda functions are particularly useful when you need a simple function for a short period, avoiding the need for a full `def` statement.

3. Functions as Arguments to Other Functions (Higher-Order Functions)

A higher-order function is a function that takes another function as an argument or returns a function as its result. This is a cornerstone of functional programming.
Functions as Arguments to Other Functions (Higher-Order Functions) in python def apply_function(func, value): """Applies a function to a value and returns the result.""" return func(value) def my_square(x): return x * x def my_cube(x): return x * x * x # Pass functions as arguments squared = apply_function(my_square, 4) # squared will be 16 cubed = apply_function(my_cube, 4) # cubed will be 64 print(f"Squared: {squared}, Cubed: {cubed}") #Using Lambda function as an argument doubled = apply_function(lambda x: x * 2, 5) #doubled will be 10 print(f"Doubled: {doubled}")

Output

Squared: 16, Cubed: 64 Doubled: 10
`apply_function` is a higher-order function because it accepts `func` (another function) as an argument.

4. Functions Returning Functions (Closures)

Functions can also return other functions. The returned function can "remember" its surrounding environment (the variables in the enclosing function's scope), a concept known as a closure.
Python - Functions Returning Functions (Closures) def create_multiplier(factor): """Returns a function that multiplies its input by a given factor.""" def multiplier(x): return x * factor return multiplier double = create_multiplier(2) triple = create_multiplier(3) print(double(5)) print(triple(5))

Output

10 15
`create_multiplier` returns a new function (`multiplier`) each time it's called. The returned function "closes over" the `factor` variable, retaining its value even after `create_multiplier` has finished executing.

5. Functions in Data Structures

Functions can be stored in lists, dictionaries, or other data structures.
Python Functions in Data Structures operations = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y } operation = operations["+"] result = operation(10, 5) print(result)

Output

15
This example demonstrates a dictionary where keys are operation symbols and values are lambda functions performing the corresponding operations.

Tutorials